import 'dart:convert';
import 'dart:developer' as developer;
import '../../shared/storage/storage_service.dart';
import '../models/chat_message.dart';

/// 聊天消息存储服务
/// 负责消息的本地持久化存储和加载
class ChatMessageStorageService {
  final StorageService _storageService;

  ChatMessageStorageService(this._storageService);

  /// 获取消息存储键名
  Future<String> getMessagesStorageKey(String? userId) async {
    if (userId == null || userId.isEmpty) {
      throw Exception('无法获取用户ID，请先登录');
    }
    return await _storageService.getMessagesStorageKey(userId);
  }

  /// 保存消息列表到本地存储
  Future<void> saveMessages(String userId, List<ChatMessage> messages) async {
    try {
      if (messages.isEmpty) {
        developer.log('⚠️ 保存消息时，消息列表为空，跳过保存', name: 'ChatMessageStorage');
        return;
      }

      // 转换为Map列表
      final messagesJson = messages.map((msg) => msg.toJson()).toList();
      
      // 保存到存储
      await _storageService.saveMessages(userId, messagesJson);
      
      final dataSize = jsonEncode(messagesJson).length;
      developer.log(
        '💾 消息已保存到本地存储: userId=$userId, messageCount=${messages.length}, dataSize=$dataSize 字节',
        name: 'ChatMessageStorage',
      );
    } catch (e) {
      developer.log('❌ 保存消息失败: $e', name: 'ChatMessageStorage');
      rethrow;
    }
  }

  /// 从本地存储加载消息列表
  Future<List<ChatMessage>> loadMessages(String userId) async {
    try {
      final messagesJson = await _storageService.loadMessages(userId);
      
      if (messagesJson.isEmpty) {
        developer.log('📖 本地存储中没有消息', name: 'ChatMessageStorage');
        return [];
      }

      // 转换为ChatMessage列表
      final messages = messagesJson.map((json) {
        try {
          return ChatMessage.fromJson(json);
        } catch (e) {
          developer.log('⚠️ 解析消息失败: $e, json: $json', name: 'ChatMessageStorage');
          return null;
        }
      }).whereType<ChatMessage>().toList();

      developer.log(
        '📖 从本地存储加载消息: userId=$userId, messageCount=${messages.length}',
        name: 'ChatMessageStorage',
      );

      return messages;
    } catch (e) {
      developer.log('❌ 加载消息失败: $e', name: 'ChatMessageStorage');
      return [];
    }
  }

  /// 清空指定用户的消息缓存
  Future<void> clearMessages(String userId) async {
    try {
      await _storageService.clearMessages(userId);
      developer.log('🗑️ 已清空用户消息缓存: $userId', name: 'ChatMessageStorage');
    } catch (e) {
      developer.log('❌ 清空消息缓存失败: $e', name: 'ChatMessageStorage');
      rethrow;
    }
  }
}


